package cn.xiangxiang.controller;

import cn.xiangxiang.service.goods.SkuService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class SearchController {

    @Reference
    private SkuService skuService;

    @RequestMapping("/search")
    public String search(Model model, @RequestParam Map<String,String> searchMap) throws Exception {
        searchMap = WebUtil.convertCharsetToUTF8(searchMap);


        if(searchMap.get("pageNo")==null){
            searchMap.put("pageNo", "1");
        }

        if(searchMap.get("orderName")==null){
            searchMap.put("orderName", "");
        }


        Map<String, Object> result = skuService.search(searchMap);

        model.addAttribute("result",result);

//        总页数
        Integer pageTotal = (Integer) result.get("pageTatol");


        Integer startPage = 1;

        Integer endPage = pageTotal;
        if(pageTotal>=5){
            startPage = Integer.valueOf((String)searchMap.get("pageNo"))  - 2;
            if(startPage<1){
                startPage = 1;
            }
        }
        endPage = startPage+4;

        model.addAttribute("endPage",endPage);
        model.addAttribute("startPage",startPage);

        model.addAttribute("pageNo",Integer.valueOf((String)searchMap.get("pageNo")));



        StringBuffer url = new StringBuffer();
        url.append("/search.do?");
        for (String key : searchMap.keySet()) {
            url.append("&").append(key).append("=").append(searchMap.get(key));
        }
        model.addAttribute("url",url);

        model.addAttribute("searchMap",searchMap);
        return "search";
    }
}
